package com.me.common.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;

/**
 * cemu2 图形插件需要 UTF8 编码，把旧的 GB2312 转成 UTF
 */
public class Gbk2UTF {

    public static void main(String[] args) {
        Path startDir = Paths.get("D:\\WiiU\\Cemu-v2\\graphicPacks\\BreathOfTheWild_Linkle3_5");

        // 开始递归查找并处理文件
        try {
            Files.walkFileTree(startDir, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    // 查找名为 rules.txt 的文件
                    if (file.getFileName().toString().equals("rules.txt")) {
                        convertFileEncoding(file);
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void convertFileEncoding(Path filePath) {
        String encodingFrom = "GB2312"; // 原始编码
        String encodingTo = "UTF-8"; // 目标编码
        String lineSeparator = "\n"; // 强制使用 LF 作为换行符

        List<String> lines = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(Files.newInputStream(filePath), encodingFrom))) {
            String line;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(filePath), encodingTo))) {
            for (String line : lines) {
                writer.write(line);
                writer.write(lineSeparator); // 写入 LF 作为换行符
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
